package com.ruoyi.common.utils.sign;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Md5加密方法
 *
 * @author ruoyi
 */
public class Md5Utils {
    private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);

    private static byte[] md5(String s) {
        MessageDigest algorithm;
        try {
            algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(s.getBytes("UTF-8"));
            byte[] messageDigest = algorithm.digest();
            return messageDigest;
        } catch (Exception e) {
            log.error("MD5 Error...", e);
        }
        return null;
    }

    private static final String toHex(byte hash[]) {
        if (hash == null) {
            return null;
        }
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;

        for (i = 0; i < hash.length; i++) {
            if ((hash[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString(hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

    public static String hash(String s) {
        try {
            return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
        } catch (Exception e) {
            log.error("not supported charset...{}", e);
            return s;
        }
    }


    /**
     * 获取安卓原生新设备指纹Md5
     *
     * @param buf  参数+phoneBrand+phoneModel
     * @return
     */
    public static String getAndroidNativeMD5(String buf) {
        MessageDigest digest;
        buf = buf.toLowerCase();
        try {
            digest = MessageDigest.getInstance("MD5");
            digest.update(buf.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
            return buf;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        String tempString = bigInt.toString(16);
        String retString = "";
        if (tempString.length() < 32) {
            int j = 32 - tempString.length();
            for (int i = 0; i < j; i++) {
                retString = "0" + retString;
            }
            retString = retString + tempString;
        } else {
            retString = tempString;
        }
        return retString;
    }


    public static void main(String[] args) {
        String androidNativeMD5 = Md5Utils.getAndroidNativeMD5("e779fe50-333f-4a7c-9480-f545e3cba2f0" + "TECNO MOBILE LIMITED" + "TECNO KE7");
        System.err.println(androidNativeMD5);


        String androidNativeMD52 = Md5Utils.getAndroidNativeMD5("e779fe50-333f-4a7c-9480-f545e3cba2f0" + "tecno" + "tecno ke7");
        System.err.println(androidNativeMD52);
    }

}
